package hot;

import java.util.ArrayList;
import java.util.List;

public class yiyisi {
    //https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/solutions/2992172/liang-chong-fang-fa-tou-cha-fa-fen-zhi-p-h9bg/?envType=study-plan-v2&envId=top-100-liked
     static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }


        static List<Integer> ret=new ArrayList<>();
        public static void flatten(TreeNode root) {
            pretravle(root);
            dfs(root,0);
        }
        public static void pretravle(TreeNode root){
            if(root==null){
                return;
            }
            ret.add(root.val);
            pretravle(root.left);
            pretravle(root.right);
        }
    public static void dfs(TreeNode root,int pos){
        if(pos==ret.size()){
            return;
        }
        root.left=null;
        if(pos+1<ret.size()){
            root.right=new TreeNode(ret.get(pos+1));
            dfs(root.right,pos+1);
        }else{
            root.right=null;
            return;
        }
    }

    public static void main(String[] args) {
        TreeNode treeNode1=new TreeNode(1);
        TreeNode treeNode2=new TreeNode(2);
        TreeNode treeNode3=new TreeNode(3);
        TreeNode treeNode4=new TreeNode(4);
        TreeNode treeNode5=new TreeNode(5);
        TreeNode treeNode6=new TreeNode(6);
        treeNode1.left=treeNode2;
        treeNode1.right=treeNode5;
        treeNode2.left=treeNode3;
        treeNode2.right=treeNode4;
        treeNode5.right=treeNode6;
        flatten(treeNode1);
        System.out.println(ret);
    }
    }

